<template>
  <div>
    <h1>资源管理页面</h1>
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="请输入资源名称"
          clearable
          class="search-input"
        />
        <el-select v-model="resourceType" placeholder="选择资源类型" class="search-select">
          <el-option label="人力" value="人力"></el-option>
          <el-option label="物力" value="物力"></el-option>
          <el-option label="财力" value="财力"></el-option>
        </el-select>
        <el-button type="primary" @click="fetchResources">搜索</el-button>
      </div>

      <!-- 数据表格 -->
      <el-table :data="resources" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="资源ID" width="80" />
        <el-table-column prop="resourceName" label="资源名称" />
        <el-table-column prop="resourceType" label="资源类型" />
        <el-table-column prop="quantity" label="数量" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="openEditDialog(scope.row)"
            >
              修改
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 修改资源弹窗 -->
    <el-dialog v-model="editDialogVisible" title="修改资源">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="资源名称">
          <el-input v-model="editForm.resourceName" placeholder="请输入资源名称" />
        </el-form-item>
        <el-form-item label="资源类型">
          <el-select v-model="editForm.resourceType" placeholder="选择资源类型">
            <el-option label="人力" value="人力"></el-option>
            <el-option label="物力" value="物力"></el-option>
            <el-option label="财力" value="财力"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量">
          <el-input type="number" v-model="editForm.quantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="editForm.unit" placeholder="请输入单位" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

// 状态
const resources = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const loading = ref(false);
const searchQuery = ref('');
const resourceType = ref('');

// 修改弹窗状态
const editDialogVisible = ref(false);
const editForm = reactive({
  id: null,
  resourceName: '',
  resourceType: '',
  quantity: 0,
  unit: '',
});

// 获取资源列表
const fetchResources = async () => {
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    // 构造请求参数
    const params = {
      current: currentPage.value,
      size: pageSize.value,
    };

    // 如果 resourceType 不为空，则添加到参数中
    if (resourceType.value) {
      params.resourceType = resourceType.value;
    }

    // 如果 projectId 不为空，则添加到参数中
    const projectId = null; // 假设项目ID为1，或者动态获取
    if (projectId) {
      params.projectId = projectId;
    }

    const response = await axios.get('http://localhost:8080/resource/page', {
      params,
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    const { records, total: totalRecords } = response.data.data;
    resources.value = records;
    total.value = totalRecords;
  } catch (error) {
    console.error('获取资源数据失败:', error);
    ElMessage.error('获取资源数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};
// 删除资源
const handleDelete = async (resource) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    // 确认删除操作
    await ElMessageBox.confirm(
      `确定要删除资源 "${resource.resourceName}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 调用删除接口
    await axios.delete(`http://localhost:8080/resource/${resource.id}`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    ElMessage.success('资源删除成功');
    fetchResources(); // 刷新资源列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除资源失败:', error);
      ElMessage.error('删除资源失败，请稍后重试');
    }
  }
};

// 打开修改资源弹窗
const openEditDialog = (resource) => {
  editForm.id = resource.id;
  editForm.resourceName = resource.resourceName;
  editForm.resourceType = resource.resourceType;
  editForm.quantity = resource.quantity;
  editForm.unit = resource.unit;
  editDialogVisible.value = true;
};

// 提交修改资源
const submitEdit = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    await axios.put(
      'http://localhost:8080/resource/update',
      {
        id: editForm.id,
        resourceName: editForm.resourceName,
        resourceType: editForm.resourceType,
        quantity: editForm.quantity,
        unit: editForm.unit,
      },
      {
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
      }
    );

    ElMessage.success('资源修改成功');
    editDialogVisible.value = false;
    fetchResources(); // 刷新资源列表
  } catch (error) {
    console.error('修改资源失败:', error);
    ElMessage.error('修改资源失败，请稍后重试');
  }
};

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchResources();
};

// 页面加载时获取数据
fetchResources();
</script>

<style scoped>
.box-card {
  margin: 20px;
  padding: 20px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.search-select {
  width: 200px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>